package com.runfast.paotui.web.controller.sys;


import com.runfast.common.utils.SessionContext;
import com.runfast.common.utils.SpringUtils;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.controller.BaseController;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.common.web.shiro.JsonAuthenticationFilter;
import com.runfast.common.web.shiro.UrlPermission;
import com.runfast.paotui.dao.model.Account;
import com.runfast.paotui.service.AccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Api("swaggerDemoController相关的api")
@RestController
@RequestMapping("/api/sys/account")
public class AccountController extends BaseController<Account, Integer> {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/login")
    public Result login() {
        Subject subject = SecurityUtils.getSubject();
        boolean authenticated = subject.isAuthenticated();
        if (authenticated) {
            return Result.ok("已经登录，请勿重复登录");
        }
        String authenticationException = (String) RequestContextHolder.currentRequestAttributes().getAttribute(JsonAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, RequestAttributes.SCOPE_REQUEST);
//        Boolean success = (Boolean)RequestContextHolder.currentRequestAttributes().getAttribute("shiro.login.success", RequestAttributes.SCOPE_REQUEST);
        if (authenticationException != null) {
            return Result.fail(ResultCode.ACCOUNT_USERNAME_OR_PASSWORD_ERROR);
        } else{
            return Result.fail(ResultCode.ACCOUNT_RELOGIN);
        }



    }

   /* @RequestMapping("/success")
    public Result success() {
        JWTCreator.Builder builder = JWT.create();
        String token = null;
        try {
            RandomStringGenerator generator = new RandomStringGenerator.Builder()
                    .withinRange('a', 'z').build();
            String randomLetters = generator.generate(9);

            builder.withIssuer(TokenUtil.ISSUER).withClaim(TokenUtil.USER_ID, SessionContext.getCurrentUser().getId()).withClaim("r",randomLetters).withIssuedAt(new Date());
            token = builder.sign(Algorithm.HMAC256(TokenUtil.SCRETE));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return Result.ok("登录成功",token);
    }*/

    @RequestMapping("/logout")
    public Result logout() {
        return Result.ok("退出成功");
    }

    @ApiOperation(value = "获取用户列表", notes = "")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @PostMapping("/permissions")
    public Result permissions() {
        ApplicationContext applicationContext = SpringUtils.getApplicationContext();
        HashMap<String, Object> hashMap = new HashMap<>();
        extractMethodMappings(applicationContext, hashMap);
        return Result.ok("", hashMap);
    }

    protected void extractMethodMappings(ApplicationContext applicationContext,
                                         Map<String, Object> result) {
        if (applicationContext != null) {
            for (Map.Entry<String, AbstractHandlerMethodMapping> bean : applicationContext
                    .getBeansOfType(AbstractHandlerMethodMapping.class).entrySet()) {
                @SuppressWarnings("unchecked")
                Map<?, HandlerMethod> methods = bean.getValue().getHandlerMethods();
                for (Map.Entry<?, HandlerMethod> method : methods.entrySet()) {
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    map.put("bean", bean.getKey());
                    HandlerMethod handlerMethod = method.getValue();
                    UrlPermission methodAnnotation = handlerMethod.getMethodAnnotation(UrlPermission.class);
                    if (methodAnnotation != null) {
                        map.put("method", handlerMethod.toString());
                        result.put(method.getKey().toString(), map);

                    }


                }
            }
        }
    }
}
